// Token.tsx
import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, Table, Modal, Form, message, Space, Select } from 'antd';
import type { FormInstance } from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import {TokenFormType, TokenRow, TokenType} from '../../types'; // 假设你已经定义了 TokenType 类型
import { ProjectType } from '../../types'; // 假设你已经定义了 ProjectType 类型
import { EnvironmentType } from '../../types'; // 假设你已经定义了 EnvironmentType 类型
import {
    addToken,
    deleteToken,
    queryToken,
    updateToken,
    tryMsg,
    useGetTokens,
    useGetProjects,
    useGetEnvironments,
    queryEnv, queryProject
} from '../../service'; // 假设你已经定义了这些服务函数
import { useSearchContext } from '../../provider/tsx';

export const Token: React.FC = () => {
    const [searchName, setSearchName] = useState<string>('');
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
    const [modalTitle, setModalTitle] = useState<string>('');
    const [currentToken, setCurrentToken] = useState<TokenFormType>({ id: 0, value: '', desc: '', projectIds: [], envIds: [] });
    const [form] = Form.useForm<TokenFormType>();
    const searchCtx = useSearchContext();

    const [tokens, setTokens] = useState<TokenRow[]>([]);
    const [projects, setProjects] = useState<ProjectType[]>([]);
    const [environments, setEnvironments] = useState<EnvironmentType[]>([]);

    useEffect(() => {
        queryToken({projectId:0,environmentId:0}).then((x) => {
            setTokens(x.data ?? []);
        });
        queryProject({}).then((x) => {
            setProjects(x.data);
        });
        queryEnv({}).then((x) => {
            setEnvironments(x.data);
        });
    }, []);

    const handleSearch = () => {
        if (!searchName) {
            message.warning('请输入 Token 名称');
            return;
        }
        const filteredTokens = tokens ? tokens.filter((token) =>
            token.desc.toLowerCase().includes(searchName.toLowerCase())
        ):[];
        setTokens(filteredTokens);
    };
    const intLoadToken = ()=>{
        queryToken({projectId:0,environmentId:0}).then((x) => {
            setTokens(x.data);
        });
    }
    const handleResetSearch = () => {
        setSearchName('');
        queryToken({projectId:0,environmentId:0}).then((x) => {
            setTokens(x.data);
        });
    };

    const handleAdd = () => {
        setModalTitle('新增 Token');
        form.setFieldsValue({ id: 0, value: '', desc: '', projectIds: [], envIds: [] });
        setCurrentToken({ id: 0, value: '', desc: '', projectIds: [], envIds: [] });
        setIsModalOpen(true);
    };
    const convertType = (record:TokenRow):TokenType=>{
        let envIds  = (record.envIds ? record.envIds.split(','):[]).map(parseInt);
        let envs =  environments.filter(x=> envIds.indexOf(x.id) > -1);

        let projectIds  = (record.projectIds ? record.projectIds.split(','):[]).map(parseInt);
        let projectFind =  projects.filter(x=> projectIds.indexOf(x.id) > -1);
        return  {
            value:record.value,
            desc:record.desc,
            envIds: envs,
            projectIds:projectFind,
        }
    }
    const convertFormType = (record:TokenRow):TokenFormType=>{
        let envIds  = (record.envIds ? record.envIds.split(','):[]).map(x=>parseInt(x));
        let envs =  environments.filter(x=> envIds.indexOf(x.id) > -1);

        let projectIds  = (record.projectIds ? record.projectIds.split(','):[]).map(x=>parseInt(x));
        let projectFind =  projects.filter(x=> projectIds.indexOf(x.id) > -1);

        return  {
            id:record.id,
            value:record.value,
            desc:record.desc,
            envIds: envs.map(x=>x.id),
            projectIds:projectFind.map(x=>x.id),
        }
    }
    const handleEdit = (record: TokenRow) => {
        let tokeType:TokenFormType = convertFormType(record)
        setModalTitle('编辑 Token');
        form.setFieldsValue(tokeType);
        setCurrentToken(tokeType);
        setIsModalOpen(true);
    };

    const handleDelete = async (row: TokenRow) => {
        tryMsg(async () => {
            console.log("ddd",row)
            await deleteToken({id:row.id})
            await intLoadToken();
            message.success('删除成功');
        });
    };
    const convertTokenTypeToRow = (type:TokenFormType):TokenRow=>{
        return {
            
            desc: type.desc, envIds: type.envIds.join(','), projectIds: type.projectIds.join(','), value: type.value
        }
    }
    const onSubmit = (values: TokenFormType ) => {
        if (currentToken.id === 0) {
            // 新增 Token
            tryMsg(async () => {
                let data: TokenFormType = { ...values };
                let tokenRow = convertTokenTypeToRow(data);
                let rsp = await addToken(tokenRow);
                const id = rsp.data;
                tokenRow.id = id;
                setTokens([tokenRow, ...tokens]);
                message.success('新增成功');
            });
        } else {
            tryMsg(async () => {
                let tokenRow = convertTokenTypeToRow({ ...currentToken, ...values });
                console.log("update values",currentToken,tokenRow)
                tokenRow.id = currentToken.id;
                await updateToken(tokenRow);
                const newTokens = tokens.map((token) =>
                    token.id === currentToken.id ? { ...token, ...tokenRow } : token
                );
                setTokens(newTokens);
                message.success('编辑成功');
            });
        }
        setIsModalOpen(false);
    };

    const handleModalOk = async () => {
        form.submit();
    };

    const handleModalCancel = () => {
        setIsModalOpen(false);
    };

    const columns: ColumnsType<TokenRow> = [
        {
            title: 'Token 名称',
            dataIndex: 'desc',
            key: 'desc',
        },
        {
            title: 'Token ',
            dataIndex: 'value',
            key: 'value',
        },
        {
            title: '授权项目',
            dataIndex: 'projectIds',
            key: 'projectIds',
            render:(value:string, record, index)=>{
                let ids  = (value ? value.split(','):[]).map((x:string)=>x.trim()).map(x=>parseInt(x));
                console.log("projcts",projects,value,ids)
                return projects.filter(x=> ids.indexOf(x.id) > -1).map(x=>x.description).join(",")
            }
        },
        {
            title: '授权环境',
            dataIndex: 'envIds',
            key: 'envIds',
            render:(value:string, record, index)=>{
                let ids  = (value ? value.split(','):[]).map(x=>parseInt(x));
                return environments.filter(x=> ids.indexOf(x.id) > -1).map(x=>x.description).join(",")
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div>
                    <Button type="link" onClick={() => handleEdit(record)}>
                        编辑
                    </Button>
                    <Button type="link" onClick={() => handleDelete(record)}>
                        删除
                    </Button>
                </div>
            ),
        },
    ];

    return (
        <div className='w-full p-8'>
            <div style={{ marginBottom: 16 }}>
                <Space className='flex justify-end'>
                    <Input
                        placeholder="请输入 Token 名称"
                        value={searchName}
                        onChange={(e) => setSearchName(e.target.value)}
                        style={{ width: 200, marginRight: 8 }}
                    />
                    <Button type="primary" onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button onClick={handleResetSearch}>重置</Button>
                    <Button type="primary" onClick={handleAdd}>
                        新增 Token
                    </Button>
                </Space>
            </div>
            <Table<TokenRow>
                columns={columns}
                dataSource={tokens.filter(x => x.desc.toLowerCase().indexOf(searchCtx.keyword.toLowerCase()) > -1)}
                rowKey="id"
            />
            <Modal
                title={modalTitle}
                open={isModalOpen}
                onOk={handleModalOk}
                onCancel={handleModalCancel}
            >
                <Form form={form} initialValues={currentToken} onFinish={onSubmit}>
                    <Form.Item
                        name="desc"
                        label="Token 描述"
                        rules={[{ required: true, message: '请输入 Token 描述' }]}
                    >
                        <Input.TextArea />
                    </Form.Item>
                    <Form.Item
                        name="value"
                        label="Token 值"

                    >
                        <Input disabled={true} />
                    </Form.Item>

                    <Form.Item
                        name="projectIds"
                        label="项目"
                        rules={[{ required: true, message: '请选择项目' }]}
                    >
                        <Select
                            mode="multiple"
                            placeholder="请选择项目"
                            options={projects.map(project => ({
                                label: project.description,
                                value: project.id
                            }))}
                        />
                    </Form.Item>
                    <Form.Item
                        name="envIds"
                        label="环境"
                        rules={[{ required: true, message: '请选择环境' }]}
                    >
                        <Select
                            mode="multiple"
                            defaultValue={currentToken.envIds.map(x=>x.id)}

                            placeholder="请选择环境"
                            options={environments.map(environment => ({
                                label: environment.description,
                                value: environment.id
                            }))}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};